'''
Created on Jun 23, 2011

@author: oabalbin
'''
import sys
from optparse import OptionParser
from collections import defaultdict

def read_file(ifile, ofile):
    '''
    '''
    ifile = open(ifile)
    ofile_129 =open(ofile.replace('.pos','_db129.pos'),'w')
    ofile_132 =open(ofile.replace('.pos','_db132.pos'),'w')
    ofile_KGPilot123 = open(ofile.replace('.pos','_KG123.pos'),'w')
    ofile_CLN = open(ofile.replace('.pos','_CLN.pos'),'w')
    
    for l in ifile:
        if l.startswith('#'):
            ofile_129.write(l)
            ofile_132.write(l)
            ofile_KGPilot123.write(l)
            ofile_CLN.write(l)
            continue
        fields=l.strip('\n').replace(',','$').split('\t')
        
        #pos= '%s@%s'%(fields[0],fields[1])
        pos= '%s@%s|%s>%s'%(fields[0],fields[1],fields[3],fields[4])
        
        info_fields = fields[7].split(';')
        info=defaultdict()
        for f in info_fields:
            t = f.split('=')
            if len(t)<2:
                info[t[0]]='nan'
            elif t[0]=="dbSNPBuildID":
                info[t[0]]=int(t[1])
            else:
                info[t[0]]=t[1]
        
        if info["dbSNPBuildID"] < 130:
            ofile_129.write(pos+',')
            ofile_132.write(pos+',')
        else:
            ofile_132.write(pos+',')
        
        if "KGPilot123" in info.keys():
            ofile_KGPilot123.write(pos+',')
        
        if "CLN" in info.keys():
            ofile_CLN
    
    ifile.close()
    ofile_129.close()
    ofile_132.close()
    ofile_KGPilot123.close()
    ofile_CLN.close()

        
            
def read_positions(ifile):
    '''
    '''
    ifile = open(ifile)
    for l in ifile:
        if l.startswith('#'):
            continue
        fields=l.strip('\n').split(',')
    
    ifile.close()
    return fields


def isec_arrays(filea,fileb):
    '''
    '''
    m1=set(read_positions(filea))
    m2=set(read_positions(fileb))
    #print sys.getsizeof(m1), sys.getsizeof(m2)
    isec=m1.intersection(m2)        
    return isec


if __name__ == '__main__':
    '''
    Write to an array the positions in a particualr vcf.
    
    '''
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-f", "--vcf_files", action="append", type="str",
                            dest="vcf_files",
                            help="others_vcf_files. Pass vcf files without .gz extention even if the file .gz is there")
    
    (options, args) = optionparser.parse_args()
    
    for ifile in options.vcf_files:
        ofile=ifile.replace('.vcf', '.pos.base')
        read_file(ifile, ofile)
        print >> sys.stderr,"DONE with file %s !"%(ifile)




